package orch

import (
	"fmt"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
)

func Run(wrapper *config.Wrapper, args []string) hcl.Diagnostics {
	if !wrapper.IsRunInStackDir && wrapper.RunInModuleName == "" {
		return errors.Diagnostics("Not explicitly specified",
			fmt.Errorf("not run in stack dir or module dir"))
	}

	if wrapper.IsRunInStackDir {
		logrus.Info("run in stack dir, change command to `run-all` stack module")
		return RunAll(wrapper, args)
	}

	flow, diags := Validate(wrapper)
	if util.HasErrors(diags) {
		return diags
	}
	flow.MarkModuleRun(wrapper.RunInModuleName)

	_, diags = runModule(wrapper, wrapper.RunInModuleName, args)
	return diags
}
